﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Concurrent;

namespace DotNET4Study
{
    public static class ConcurrentStudy
    {
        public static void Excute()
        {
            //1. 验证ConcurrentDictionary中方法的使用
            var result = ConcurrentDictionaryUsing<int>.GetOrAdd(2, x => 2 * x);
            Console.WriteLine(result);
            result = ConcurrentDictionaryUsing<int>.GetOrAdd(2, x => 3 * x);
            Console.WriteLine(result);
            result = ConcurrentDictionaryUsing<int>.AddOrUpdate(2, x => 4 * x, (x, y) => x + y);
            Console.WriteLine(result);

            //2.ConcurrentBag中放入/获取对象的使用
            ConcurrentBagUsing<int>.Add(5);
            Console.WriteLine( ConcurrentBagUsing<int>.Get(5));
        }

        public static class ConcurrentBagUsing<T>
        {
            private static ConcurrentBag<T> bag = new ConcurrentBag<T>();
            public static void Add(T t)
            {
                bag.Add(t);
            }

            public static T Get(T t)
            {
                T p= t;
                bag.TryTake(out p);
                return p;
            }
        }


        private static class ConcurrentDictionaryUsing<T>
        {
            private static ConcurrentDictionary<T, T> dic = new ConcurrentDictionary<T, T>();

            public static T GetOrAdd(T t, Func<T, T> fun)
            {
                var result = dic.GetOrAdd(t, fun);
                return result;
            }

            public static T AddOrUpdate(T t, Func<T, T> addFun, Func<T, T, T> updateFun)
            {
                var result = dic.AddOrUpdate(t, addFun, updateFun);
                return result;
            }
        }
    }

    
}
